package com.offcn.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ld
 * @date 2021/9/10 20:17
 */
@RestController
public class UploadController {
    //注入地址
    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;

    @PostMapping("/upload")
    public Result upload(@RequestParam(name = "file") MultipartFile file) {
        //1.文件名
        String filename = file.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf(".") + 1);
        //2.客户端
        try {
            FastDFSClient client = new FastDFSClient("classpath:fdfs_client.conf");
            //3.上传
            String path = client.uploadFile(file.getBytes(), extName);
            //4.拼接
           String url= FILE_SERVER_URL + path;
            System.out.println(url);
            return new Result(true, StatusCode.OK, "图片上传成功", url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "图片上传失败");
        }
    }

}
